﻿package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.method.NumberKeyListener;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.baseui.BaseActivity_NoBar;
import com.kuanter.kuanterauto.cache.ObjectCache;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.VehicleInfo;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.umeng.analytics.MobclickAgent;

/**
 * 修改车辆
 * 
 * @author soup
 * 
 */
public class XgclActivity extends BaseActivity_NoBar {
	public static final int XGCL = 1;

	public static final int XZSF = 1;
	public static final int XZPP = 2;
	public static final int XZBX = 3;

	private Button btTopLeft_xgcl = null;
	private Button bt_sheng = null;
	private Button bt_done = null;

	private EditText et_cpzm = null;// 车牌字母
	private EditText et_cpnum = null;// 车牌数字

	private RelativeLayout rl_xgxh = null;
	private TextView tv_pp = null;// 车型品牌
	private TextView tv_xh = null;// 车型型号

	private RelativeLayout rl_xgxb = null;
	private TextView tv_city = null;// 保险城市
	private TextView tv_bx = null;// 保险公司

	private RelativeLayout rl_xgsj = null;
	private TextView tv_endtiem = null;// 到期时间

	private VehicleInfo vehicleInfo = null;

	private String province = "";// 省份
	private String pp = "";// 车牌品牌
	private String xh = "";// 车牌型号
	private String city = "";// 保险城市
	private String bx = "";// 保险品牌
	private String endtiem = "";// 保险到期时间

	DatePickerDialog datepick = null;// 日期对话框
	private Calendar calendar = null;// 日历类
	private String year;
	private String month;
	private String day;

	static final int DATE_DIALOG_ID = 0;
	int index=0;
	private boolean isUpdate=false;
	DataLoader dataLoader=null;
	InputMethodManager m = null;
	
	
	Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case HttpTask.RESULT_OK:
				finishProgress();
				isUpdate=true;
				showToast("修改成功");
				Intent intent=new Intent();
				intent.putExtra("update", isUpdate);
				setResult(XgclActivity.XGCL, intent);
				finish();
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				isUpdate=false;
				showToast("修改失败");
				break;
			}
		}
	};

	private String userId;

	private int carInfoIndex;

	private List<VehicleInfo> vehicleInfos;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.xgcl);
		
		dataLoader=new DataLoader(this);

		carInfoIndex = getIntent().getIntExtra("carInfoIndex", 0);
		vehicleInfos = (List<VehicleInfo>)ObjectCache.get("vehicleInfos");
		vehicleInfo = vehicleInfos.get(carInfoIndex);
		calendar = Calendar.getInstance();
		initView();
		initListener();
		m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
	}

	// {"status":true,
	// "vehicleInfoList":
	// [{"id":95559,"insuranceCity":"武汉","insuranceCompany":"大地保险",
	// "insuranceStartTime":"2013-02-26","licensePlateNumber":"渝A11555","vehicleBrand":"阿尔法·罗米欧","vehicleModels":"156"}]}
	private void initView() {
		btTopLeft_xgcl = (Button) findViewById(R.id.btTopLeft_xgcl);
		bt_sheng = (Button) findViewById(R.id.bt_sheng);
		bt_done = (Button) findViewById(R.id.bt_done);
		et_cpzm = (EditText) findViewById(R.id.et_cpzm);
		et_cpnum = (EditText) findViewById(R.id.et_cpnum);
		rl_xgxh = (RelativeLayout) findViewById(R.id.rl_xgxh);
		rl_xgxb = (RelativeLayout) findViewById(R.id.rl_xgxb);
		rl_xgsj = (RelativeLayout) findViewById(R.id.rl_xgsj);
		tv_pp = (TextView) findViewById(R.id.tv_pp);
		tv_xh = (TextView) findViewById(R.id.tv_xh);
		tv_city = (TextView) findViewById(R.id.tv_city);
		tv_bx = (TextView) findViewById(R.id.tv_bx);
		tv_endtiem = (TextView) findViewById(R.id.tv_endtiem);
		
//		private String pp = "";// 车牌品牌
//		private String xh = "";// 车牌型号
//		private String city = "";// 保险城市
//		private String bx = "";// 保险品牌
//		private String endtiem = "";// 保险到期时间

		
//		Pattern p=Pattern.compile("^[\u4e00-\u9fa5]");
//		Matcher m = p.matcher(vehicleInfo.getLicensePlateNumber().substring(0, 1));
		if (isHanZi(vehicleInfo.getLicensePlateNumber().substring(0, 1))){
			bt_sheng.setText(vehicleInfo.getLicensePlateNumber().substring(0, 1));
			province=vehicleInfo.getLicensePlateNumber().substring(0, 1);
			et_cpzm.setText(vehicleInfo.getLicensePlateNumber().substring(1, 2));
			et_cpnum.setText(vehicleInfo.getLicensePlateNumber().substring(2,vehicleInfo.getLicensePlateNumber().length()));
		}else{
			province="";
			if(isE(vehicleInfo.getLicensePlateNumber().substring(0, 1))){
			et_cpzm.setText(vehicleInfo.getLicensePlateNumber().substring(0, 1));
			et_cpnum.setText(vehicleInfo.getLicensePlateNumber().substring(1,vehicleInfo.getLicensePlateNumber().length()));
			}else{
				et_cpzm.setText("");
				et_cpnum.setText(vehicleInfo.getLicensePlateNumber().substring(0,vehicleInfo.getLicensePlateNumber().length()));
			}
		}
		// {"status":true,
					// "vehicleInfoList":
					// [{"id":95559,"insuranceCity":"武汉","insuranceCompany":"大地保险",
					// "insuranceStartTime":"2013-02-26","licensePlateNumber":"渝A11555","vehicleBrand":"阿尔法·罗米欧","vehicleModels":"156"}]}
		
//		et_cpzm.setText(vehicleInfo.getLicensePlateNumber().substring(1, 2));
		
//		tv_pp.setText(vehicleInfo.getVehicleBrand().equals("")?"暂无信息":vehicleInfo.getVehicleBrand());
//		tv_xh.setText(vehicleInfo.getVehicleModels().equals("")?"暂无信息":vehicleInfo.getVehicleModels());
		
		if(!vehicleInfo.getVehicleBrand().equals("")&&!vehicleInfo.getVehicleBrand().equals("null")){
			tv_pp.setText(vehicleInfo.getVehicleBrand());
			pp=vehicleInfo.getVehicleBrand();
		}else{
			tv_pp.setText("");
			pp="";
		}
		
		if(!vehicleInfo.getVehicleModels().equals("")&&!vehicleInfo.getVehicleModels().equals("null")){
			tv_xh.setText(vehicleInfo.getVehicleModels());
			xh=vehicleInfo.getVehicleModels();
		}else{
			tv_xh.setText("");
			xh="";
		}
		
		
//		if(!vehicleInfo.getInsuranceCity().equals("null")&&!vehicleInfo.getInsuranceCompany().equals("null")){
//		tv_city.setText(vehicleInfo.getInsuranceCity());
//		tv_bx.setText(vehicleInfo.getInsuranceCompany());
//		}else{
//			tv_city.setText("");
//			tv_bx.setText("");
//		}
//			tv_city.setText(vehicleInfo.getInsuranceCity().equals("null")?"暂无信息":vehicleInfo.getInsuranceCity());
//			tv_bx.setText(vehicleInfo.getInsuranceCompany().equals("null")?"暂无信息":vehicleInfo.getInsuranceCompany());
			
			if(!vehicleInfo.getInsuranceCity().equals("")&&!vehicleInfo.getInsuranceCity().equals("null")){
				tv_city.setText(vehicleInfo.getInsuranceCity());
				city=vehicleInfo.getInsuranceCity();
			}else{
				tv_city.setText("暂无信息");
				city="";
			}
			
			if(!vehicleInfo.getInsuranceCompany().equals("")&&!vehicleInfo.getInsuranceCompany().equals("null")){
				tv_bx.setText(vehicleInfo.getInsuranceCompany());
				bx=vehicleInfo.getInsuranceCompany();
			}else{
				tv_bx.setText("暂无信息");
				bx="";
			}
			
		String date[] = vehicleInfo.getInsuranceStartTime().split("-");
		if (date.length == 3) {
			tv_endtiem.setText(date[0] + "年" + date[1] + "月" + date[2] + "日到期");
		}else{
			tv_endtiem.setText("暂无信息");
		}
		
//		pp=vehicleInfo.getVehicleBrand();
//		xh=vehicleInfo.getVehicleModels();
//		city=vehicleInfo.getInsuranceCity();
//		bx=vehicleInfo.getInsuranceCompany();
		
		if(!vehicleInfo.getInsuranceStartTime().equals("")&&!vehicleInfo.getInsuranceStartTime().equals("null")){
			endtiem=vehicleInfo.getInsuranceStartTime();
		}else{
			endtiem="";
		}
//		android:inputType="textUri|textMultiLine"
		
        
		
		et_cpzm.setKeyListener(new NumberKeyListener() {
			// 0无键盘 1英文键盘 2模拟键盘 3数字键盘
			@Override
			public int getInputType() {
			return 1;
			}
			// 返回允许输入的字符
			@Override
			protected char[] getAcceptedChars() {
			// TODO Auto-generated method stub
			char[] c = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','L','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','l','s','t','u','v','w','x','y','z'};
			return c;
			}
			});
		et_cpnum.setKeyListener(new NumberKeyListener() {
			// 0无键盘 1英文键盘 2模拟键盘 3数字键盘
			@Override
			public int getInputType() {
				return 1;
			}
			// 返回允许输入的字符
			@Override
			protected char[] getAcceptedChars() {
				// TODO Auto-generated method stub
				char[] c = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','L','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','l','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'};
				return c;
			}
		});
		
		et_cpzm.setSelection(et_cpzm.getText().toString().length());
		
		et_cpnum.setSelection(et_cpnum.getText().toString().length());
	}

	private void initListener() {
		btTopLeft_xgcl.setOnClickListener(this);
		bt_sheng.setOnClickListener(this);
		bt_done.setOnClickListener(this);
		rl_xgxh.setOnClickListener(this);
		rl_xgxb.setOnClickListener(this);
		rl_xgsj.setOnClickListener(this);
	}
	
	@Override
	protected void onResume() {
		
		
		
		et_cpzm.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if(!hasFocus){
					et_cpzm.setText(et_cpzm.getText().toString().toUpperCase());
				}
			}
		});
		
		et_cpnum.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if(!hasFocus){
					et_cpnum.setText(et_cpnum.getText().toString().toUpperCase());
				}
			}
		});
		
		MobclickAgent.onResume(this);
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		
		MobclickAgent.onPause(this);
		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
		m.hideSoftInputFromWindow(et_cpnum.getWindowToken(), 0);
		m.hideSoftInputFromWindow(et_cpzm.getWindowToken(), 0);
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btTopLeft_xgcl:
			m.hideSoftInputFromWindow(et_cpnum.getWindowToken(), 0);
			m.hideSoftInputFromWindow(et_cpzm.getWindowToken(), 0);
			finish();
			break;
		case R.id.bt_sheng:// 选择省份
			et_cpzm.setText(et_cpzm.getText().toString().toUpperCase());
			et_cpnum.setText(et_cpnum.getText().toString().toUpperCase());
			qStartActivityForResult(XzsfActivity.class, null, XZSF);
			break;
		case R.id.delete_car_info_btn:
			dataLoader = new DataLoader(this);
		//	dataLoader.DisplayData(HttpConfigAPI.SERVER_URL+HttpConfigAPI., params, handler, id, isc);
			//待定
			break;
		case R.id.bt_done:// 完成
			et_cpzm.setText(et_cpzm.getText().toString().toUpperCase());
			et_cpnum.setText(et_cpnum.getText().toString().toUpperCase());
			if(pp.equals("")){
				showToast("请选择汽车品牌");
				break;
			}else if(xh.equals("")){
				showToast("请选择汽车型号");
				break;
			}else if(et_cpzm.getText().toString().length()<1){
				showToast("输入车牌");
				break;
			}else if(et_cpnum.getText().toString().length()!=5){
				showToast("输入正确的车牌");
				break;
			}else if(city.equals("")){
				showToast("选择保险城市");
				break;
			}else if(bx.equals("")){
				showToast("选择保险公司");
				break;
			}else if(endtiem.equals("")){
				showToast("选择保险时间");
				break;
			}else if(province.equals("")){
				showToast("选择车牌省份");
				break;
			}else{
			showProgress("更新中...");
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("vehicleInfo.id", vehicleInfo.getId()));
			SharedPreferences sp = getSharedPreferences(SharePrefenceUtil.USERINFO,MODE_PRIVATE);
			userId = sp.getString("id", "");
			params.add(new BasicNameValuePair("vehicleInfo.userId", userId+""));
			params.add(new BasicNameValuePair("vehicleInfo.vehicleBrand", pp));
			params.add(new BasicNameValuePair("vehicleInfo.vehicleModels", xh));
			params.add(new BasicNameValuePair("vehicleInfo.licensePlateNumber", province+et_cpzm.getText().toString().toUpperCase()+et_cpnum.getText().toString().toUpperCase()));
			params.add(new BasicNameValuePair("vehicleInfo.insuranceCity", city));
			params.add(new BasicNameValuePair("vehicleInfo.insuranceCompany", bx));
			params.add(new BasicNameValuePair("vehicleInfo.insuranceStartTime", endtiem));
//			String result=HttpUtil.requestStringForPost(MainConstants.HOST+"vehicleInfo/update_vehicle", params);
//			try {
//				if(StringUtils.isSuccess(result)){
//					finishProgress();
//					isUpdate=true;
//					showToast("修改成功");
//				}else{
//					finishProgress();
//					isUpdate=false;
//					showToast("修改失败");
//				}
//			} catch (JSONException e) {
//				e.printStackTrace();
//			}
			
			dataLoader.DisplayData(MainConstants.HOST_test+"vehicleInfo/update_vehicle", params, handler, "",false);
			}
			break;
		case R.id.rl_xgxh:// 选择车型
			et_cpzm.setText(et_cpzm.getText().toString().toUpperCase());
			et_cpnum.setText(et_cpnum.getText().toString().toUpperCase());
			qStartActivityForResult(XgcxActivity.class, null, XZPP);
			break;
		case R.id.rl_xgxb:// 选择保险
			et_cpzm.setText(et_cpzm.getText().toString().toUpperCase());
			et_cpnum.setText(et_cpnum.getText().toString().toUpperCase());
			qStartActivityForResult(XzbxActivity.class, null, XZBX);
			break;
		case R.id.rl_xgsj:// 选择日期
			et_cpzm.setText(et_cpzm.getText().toString().toUpperCase());
			et_cpnum.setText(et_cpnum.getText().toString().toUpperCase());
			showDialog(DATE_DIALOG_ID);
			break;
		}
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			String date[] = vehicleInfo.getInsuranceStartTime().split("-");
			if (date.length == 3) {
				datepick = new DatePickerDialog(this, mSetDateListener,
						Integer.parseInt(date[0]), Integer.parseInt(date[1])-1,
						Integer.parseInt(date[2]));
			} else {
				datepick = new DatePickerDialog(this, mSetDateListener,
						calendar.get(Calendar.YEAR),
						calendar.get(Calendar.MONTH),
						calendar.get(Calendar.DAY_OF_MONTH));
			}
			return datepick;
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener mSetDateListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int myear, int monthOfYear,
				int dayOfMonth) {
			year = myear + "";
			month = monthOfYear + 1 + "";
			day = dayOfMonth + "";

			calendar.set(Calendar.YEAR, myear);
			calendar.set(Calendar.MONTH, monthOfYear);
			calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			// week = int_to_str(calendar.get(Calendar.DAY_OF_WEEK));
			endtiem = year + "-" + month + "-" + day;
			tv_endtiem.setText(year + "年" + month + "月" + day + "日到期");

		}
		// }
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		try {
			switch (resultCode) {
			case XZSF:// 返回省份
				province = data.getStringExtra("province");
				bt_sheng.setText(province);
				break;
			case XZPP:// 选择品牌
				pp = data.getStringExtra("pp");
				xh = data.getStringExtra("xh");
				tv_pp.setText(pp);
				tv_xh.setText(xh);
				break;
			case XZBX:
				city=data.getStringExtra("city");
				bx=data.getStringExtra("bx");
				tv_city.setText(city);
				tv_bx.setText(bx);
				break;
			}

		} catch (Exception e) {
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

}

